﻿using MyMusicPlayer.Domain;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace MyMusicPlayer.Utils
{
    class XMLHelper
    {
        /// <summary>
        /// 生成XML文件，用作配置文件，保存播放列表
        /// <?xml version = "1.0" encoding="UTF-8"?>
        /// <root>
        ///   <info volume="0.5"/>
        ///   <playlist />
        /// </root>
        /// </summary>
        public static void CreatePlaylistFile()
        {
            if (!File.Exists(GlobalVariable.PLAYLIST_FULL_PATH))
            {
                XmlDocument doc = new XmlDocument();

                XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                XmlElement header = doc.DocumentElement;
                doc.InsertBefore(xmlDeclaration, header);

                XmlElement root = doc.CreateElement("root");
                doc.AppendChild(root);

                XmlElement info = doc.CreateElement("info"); // 用于存放其他相关信息，相当于元数据
                info.SetAttribute("volume", "0.5"); // 默认的音量值
                root.AppendChild(info);

                XmlElement playlist = doc.CreateElement("playlist"); // 播放列表
                root.AppendChild(playlist);

                doc.Save(GlobalVariable.PLAYLIST_FULL_PATH);
                System.Console.WriteLine("创建配置文件，记录播放列表。");
            }
        }


        /// <summary>
        /// 添加音乐文件到播放列表时，保存该文件信息到配置文件中。
        /// </summary>
        /// <param name="fullPath"></param>
        public static void AddToPlaylistCache(MusicInfo musicInfo)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(GlobalVariable.PLAYLIST_FULL_PATH);
            XmlNode playlist = xmlDoc.SelectSingleNode("root/playlist");
            XmlElement music = xmlDoc.CreateElement("music");
            //music.SetAttribute("index", musicInfo.Index.ToString()); // Index属性不入库，防止删除音乐时多个节点Index要减一的问题
            music.SetAttribute("id", musicInfo.Id);
            music.SetAttribute("name", musicInfo.Name);
            music.SetAttribute("artist", musicInfo.Artist);
            music.SetAttribute("album", musicInfo.Album);
            music.SetAttribute("duratioin", musicInfo.Duration.ToString());
            //music.SetAttribute("duratioinText", musicInfo.DurationText.ToString());
            music.SetAttribute("path", musicInfo.FullPath);
            playlist.AppendChild(music);
            xmlDoc.Save(GlobalVariable.PLAYLIST_FULL_PATH);
            System.Console.WriteLine("添加歌曲：" + musicInfo.FullPath);
        }


        /// <summary>
        /// 从本地XML配置文件中，获取播放列表的缓存数据。
        /// </summary>
        /// <returns></returns>
        public static ObservableCollection<MusicInfo> GetAllMusicInfoCache()
        {
            ObservableCollection<MusicInfo> list = new ObservableCollection<MusicInfo>();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(GlobalVariable.PLAYLIST_FULL_PATH);
            XmlNode playlist = xmlDoc.SelectSingleNode("root/playlist");
            XmlNodeList musiclist = playlist.ChildNodes;
            foreach (XmlNode music in musiclist)
            {
                MusicInfo musicInfo = new MusicInfo();
                //musicInfo.Index = int.Parse(music.Attributes["index"].InnerText); // Index属性不入库，防止删除音乐时多个节点Index要减一的问题
                musicInfo.Id = music.Attributes["id"].InnerText;
                musicInfo.Name = music.Attributes["name"].InnerText;
                musicInfo.Artist = music.Attributes["artist"].InnerText;
                musicInfo.Album = music.Attributes["album"].InnerText;
                musicInfo.Duration = int.Parse(music.Attributes["duratioin"].InnerText);
                //musicInfo.DurationText = int.Parse(music.Attributes["duratioinText"].InnerText);
                musicInfo.DurationText = TimeHelper.Second2MinuteSecond(musicInfo.Duration);
                musicInfo.FullPath = music.Attributes["path"].InnerText;
                list.Add(musicInfo);
            }
            System.Console.WriteLine("获取播放列表所有歌曲");
            return list;
        }

        /// <summary>
        /// 移除playlist中指定的音乐对象。
        /// </summary>
        /// <param name="musicInfo"></param>
        public static void RemoveMusicInfoItem(MusicInfo musicInfo)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(GlobalVariable.PLAYLIST_FULL_PATH);
            XmlNode playlist = xmlDoc.SelectSingleNode("root/playlist");
            XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("root/playlist/music[@id='"+ musicInfo.Id +"']");
            if (element != null)
            {
                element.ParentNode.RemoveChild(element);
                xmlDoc.Save(GlobalVariable.PLAYLIST_FULL_PATH);
                System.Console.WriteLine("移除歌曲：" + musicInfo.FullPath);
            }
        }

        /// <summary>
        /// 清空播放列表
        /// </summary>
        public static void RemoveAllMusicInfoItem()
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(GlobalVariable.PLAYLIST_FULL_PATH);
            XmlNode playlist = xmlDoc.SelectSingleNode("root/playlist");
            playlist.RemoveAll();
            xmlDoc.Save(GlobalVariable.PLAYLIST_FULL_PATH);
            System.Console.WriteLine("清空播放列表！");
        }

        /// <summary>
        /// 打开软件时，获取音量值
        /// </summary>
        /// <returns></returns>
        public static double GetVolume()
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(GlobalVariable.PLAYLIST_FULL_PATH);
            XmlNode info = xmlDoc.SelectSingleNode("root/info");
            XmlAttributeCollection attrColl = info.Attributes;
            double volume = 0.5;  // 默认音量值
            foreach (XmlAttribute attr in attrColl)
            {
                if (attr.Name.Equals(GlobalVariable.VOLUME_NODE))
                {
                    volume = double.Parse(attr.Value);
                    System.Console.WriteLine("获取音量值：" + volume);
                    break; 
                }
            }
            return volume;
        }

        /// <summary>
        /// 退出软件时，记录音量值
        /// </summary>
        /// <param name="volume"></param>
        public static void SetVolume(double volume)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(GlobalVariable.PLAYLIST_FULL_PATH);
            XmlElement info = (XmlElement)xmlDoc.SelectSingleNode("root/info");
            info.SetAttribute(GlobalVariable.VOLUME_NODE, volume.ToString());
            xmlDoc.Save(GlobalVariable.PLAYLIST_FULL_PATH);
            System.Console.WriteLine("保存音量值：" + volume);
        }
    }
}
